// pages/center/clock-in/clock-in.js
const key = 'CV6BZ-WWT2X-7R747-ZVKJD-DNMWZ-2OBMN'; //使用在腾讯位置服务申请的key
const referer = 'SDAAS运营助手'; //调用插件的app的名称
const chooseLocation = requirePlugin('chooseLocation');
var QQMapWX = require('../../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;
var verify = require('../../../utils/verify-token.js')
var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
 data:{
   latitude:'',
   longitude:'',
   array: [],
   index:0,
   locationName: '',
   identifier: ''
 },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
	 qqmapsdk = new QQMapWX({
			key: key
	 });
   let that = this;
   that.setData({
     sh: app.globalData.screenHeight,
     sw: app.globalData.screenWidth,
		 
   })
   that.clockInType();
  },
  choseLocation(){
    wx.navigateTo({
      url: 'plugin://chooseLocation/index?key=' + key + '&referer=' + referer
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let that = this;
    wx.getLocation({
      type: 'wgs84',
      success(res) {
       // console.log(res)
        const latitude = res.latitude;
        const longitude = res.longitude;
				let location = {
					latitude:latitude,
					longitude:longitude
				};
        that.setData({
          latitude: latitude,
          longitude: longitude,
          markers: [{
            iconPath: "../../../images/location_g.png",
            // id: 0,
            latitude: latitude,
            longitude: longitude,
            width: 50,
            height: 50
          }]
        })
        that.reverseGeocoder(location);
        // console.log(latitude)
        // console.log(longitude)
      }
    })
  },
  //地址解析
  reverseGeocoder:function(loc){
    let that = this;
    qqmapsdk.reverseGeocoder({
      location:loc,
      success: function (res) {//成功后的回调
        //console.log(res);
				that.setData({
          locationName: res.result.formatted_addresses.recommend,
          clockInAddress:res.result.address
				})       
      },
      fail: function (error) {
        console.error(error);
      },
      complete: function (res) {
        //console.log(res);
      }
    })
  },
  //打卡类型切换
  bindPickerChange: function (e) {
   // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })

  },
  //扫设备码
  scanDev(){
    let deviceId = '';
    let that = this;
    wx.scanCode({
      success(res) {
        //console.log(res)
        let length = res.result.length
        for (var i = 0; i < length; i++) {
          if (res.result[length - i - 1] == "=") {
            break;
          }
          deviceId = res.result[length - i - 1] + deviceId
        }
        that.devInfo(deviceId);
      },
      fail() {
        console.log("扫码失败")
      }
    })
  },
  //获取设备信息
  devInfo(deviceId){
    let that = this;   
    const token = app.globalData.token
    const baseUrl = app.globalData.baseUrl; 
    wx.request({
      url: baseUrl + 'clock_in_record/applet/device/' + deviceId,
      header: {
        'AUTHORIZATION': token
      },
      success: function (res) {
        if (res.data.code == 60006) {
          verify.clearAll()
        } else if (res.data.code == 200) {
          let identifier = res.data.data.identifier;          
          that.setData({
            identifier: identifier,
            deviceId: deviceId
          })
        } else {
          wx.showModal({
            title: '操作失败',
            content: res.data.message,
          })
        }
      },
      fail:function(fail){
        console.log("设备信息获取失败")
      }
    })
  },
  //获取打卡类型
  clockInType(){
    let token = app.globalData.token
    let baseUrl = app.globalData.baseUrl;
    let that = this;
    wx.request({
      url: baseUrl + 'clock_in_record/type/list',
      header: {
        'AUTHORIZATION': token
      },
      success: function (res) {
        if (res.data.code == 60006) {
          verify.clearAll()
        } else if (res.data.code == 200) {   
          let array = res.data.data;
          array.unshift({
            clockInTypeName: '点击选择',
            clockInTypeId: ''
          })
          that.setData({
            array: array
          })
        } else {
          wx.showModal({
            title: '操作失败',
            content: res.data.message,
          })
        }
      },
      fail: function (fail) {
        console.log("设备信息获取失败")
      }
    })
  },
  //获取打卡内容的值
  bindTextAreaBlur:function(e){
    let that = this;
    //console.log(e)
    that.setData({
      clockInContent: e.detail.value
    })
  },
  //生成打卡记录
  generateClockIn(){
    
    let token = app.globalData.token
    let baseUrl = app.globalData.baseUrl;
    let that = this;
    console.log(that.data.deviceId)
    if (!that.data.deviceId) {
      wx.showModal({
        title: '提示',
        content: '请扫描打卡设备码',
      })
      return;
    }
    if(that.data.index==0){
      wx.showModal({
        title: '提示',
        content: '请选择打卡类型',
      })
      return;
    }
    let clockInAddress = that.data.clockInAddress;
    let clockInContent = that.data.clockInContent;
    let clockInName = that.data.locationName;
    let clockInTypeName = that.data.array[that.data.index].clockInTypeName;
    let deviceId = that.data.deviceId;
    let identifier = that.data.identifier;
    let latitude = that.data.latitude;
    let longitude = that.data.longitude;
    let data = {
      clockInAddress: clockInAddress,
      clockInContent: clockInContent,
      clockInName: clockInName,
      clockInTypeName: clockInTypeName,
      deviceId: deviceId,
      identifier: identifier,
      latitude: latitude,
      longitude: longitude
    };
   // console.log(data)
    wx.request({
      url: baseUrl + 'clock_in_record/applet/generate',
      header: {
        'AUTHORIZATION': token
      },
      data:data,
      method:'put',
      success: function (res) {
        if (res.data.code == 60006) {
          verify.clearAll()
        } else if (res.data.code == 200) {
         wx.showToast({
           title: '打卡成功',
         })
        } else {
          wx.showModal({
            title: '操作失败',
            content: res.data.message,
          })
        }
      },
      fail: function (fail) {
        console.log("设备信息获取失败")
      }
    })
  },
  //打卡记录跳转
  record(e){
    wx.navigateTo({
      url: 'clock-in-record/clock-in-record'
    })
  },
  
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const location = chooseLocation.getLocation();    
    let that = this;
    //console.log(location)
    if(location){
      that.setData({
        latitude: location.latitude,
        longitude: location.longitude,
        locationName:location.name,
        clockInAddress:location.address,
        markers: [{
          iconPath: "../../../images/location_g.png",
          // id: 0,
          latitude: location.latitude,
          longitude: location.longitude,
          width: 50,
          height: 50
        }]
      })
    }

    console.log(location)
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})